import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import path from "path";
import fs from "fs";
import compressPlugin from "vite-plugin-compression";

console.log(path.resolve);
// https://vitejs.dev/config/
export default defineConfig(({ mode }) => {
  return {
    base: mode === "development" ? "/" : "/vue-admin-work-x/", // 根据环境区分 base
    plugins: [
      vue(),
      {
        name: "custom-index-html",
        configureServer(server) {
          server.middlewares.use((req, res, next) => {
            if (req.url === "/") {
              const htmlPath = path.resolve(__dirname, "public/index.html");
              const htmlContent = fs.readFileSync(htmlPath, "utf-8");
              res.setHeader("Content-Type", "text/html");
              res.end(htmlContent);
            } else {
              next();
            }
          });
        },
        transformIndexHtml(html) {
          return html; // 如果需要自定义 index.html 的处理，可以在这里做
        },
      },
      compressPlugin({
        // gzip 压缩配置
        verbose: true,
        disable: false,
        threshold: 51200, // 50240 bytes 近似
        algorithm: "gzip",
        ext: ".gz",
      }),
    ],
    resolve: {
      alias: {
        "@": path.resolve(__dirname, "src"), // 配置 alias
      },
    },
    build: {
      outDir: "dist", // 输出目录
      assetsDir: "static", // 静态资源目录
      sourcemap: true, // 生产环境 source map
      rollupOptions: {
        input: {
          main: path.resolve(__dirname, "public/index.html"),
        },
        output: {
          manualChunks(id) {
            if (id.includes("node_modules")) {
              return id
                .toString()
                .split("node_modules/")[1]
                .split("/")[0]
                .toString();
            }
          },
        },
      },
    },
    server: {
      port: 5567, // 开发服务器端口
      open: true, // 自动打开浏览器
      hmr: true, // 开启 HMR 热更新
    },
  };
});
